const common = require("../../utils/common")
const server = require('../../utils/server');
const qiniuUploader = require('../../utils/qiniuUploader');
const app = getApp();
const reg = /^1(3[0-9]|4[01456789]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

function getNearly7Day() {
  let days = []
  var date = new Date()
  for (let i = 0; i <= 24 * 14; i += 24) {
    //今天加上前6天
    let dateItem = new Date(date.getTime() - i * 60 * 60 * 1000) //使用当天时间戳减去以前的时间毫秒（小时*分*秒*毫秒）
    let y = dateItem.getFullYear() //获取年份
    let m = dateItem.getMonth() + 1 //获取月份js月份从0开始，需要+1
    let d = dateItem.getDate() //获取日期
    m = addDate0(m) //给为单数的月份补零
    d = addDate0(d) //给为单数的日期补零
    let valueItem = y + '-' + m + '-' + d //组合
    days.push(valueItem) //添加至数组
  }
  //给日期加0
  function addDate0(time) {
    if (time.toString().length == 1) {
      time = '0' + time.toString()
    }
    return time
  }
  return days
}

Page({
  /**
   * 页面的初始数据
   */
  isSelectStore: false,
  selectTime: [0, 0],
  selectTypeIndex: [0],
  isCansubmit: true,
  page: 1,
  count: 10,
  data: {
    type: '',
    category: '',
    // 投诉类型
    complaintTypes: [{ val: 1, tit: '其他' }],
    // 诉求类型
    appealTypes: [{ val: 1, label: '退款' }],
    describe: '',
    images: [],
    pay_images: [],
    appeal_type: 0,
    order_id: '',
    order_code: '',
    store_id: '',
    store_name: '',
    store_number: '',
    arrival_time: '',
    contact_number: '',
    customer_name: '',
    remark: '',
    other_desc: '',
    status_name: '',
    orderList: [],
    isCheck: 0,
    dateList: [],
    timeList: [],
    storeList: [],
    orderStoreList: [],
    showStores: false,
    proitem_id:0,
    typename:'',
    proname:'',
    feedback_id:0,
    pay_status:10,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ isCheck = 0, type, category, proitem_id, typename, proname }) {
    this.setData({ isCheck,proitem_id,typename,proname })

    var options = {
        region: 'ECN',
        uptoken: '',
        uptokenURL: 'http://ljhtest.roi-cloud.com/api/feedback/gettoken',
        uptokenFunc: function () { },
        domain: 'https://static.sungivenfood.com',
        key: 'feedback',
        shouldUseQiniuFileName: false
      };
      qiniuUploader.init(options);
    if (isCheck) {
      wx.getStorage({
        key: 'myComplaint',
        success: res => {
            console.log(res.data);
          let { type, type_name, category, describe, images, appeal_type, order_code, store_name, store_number, arrival_time, contact_number, customer_name, remark, status_name,other_desc,proof_images,typename,proname,pay_images,feedback_id,pay_status,invoice_images } = res.data
          if (images && images.length) {
            images = images.map(item => {
              return {
                url: item,
                type: ['pdf', 'png', 'jpg', 'jpeg'].indexOf(item.split('.')[3]) != -1 ? 'image' : 'video'
              }
            })
          }
          if (pay_images && pay_images.length) {
            pay_images = pay_images.map(item => {
              return {
                url: item,
                type: [ 'png', 'jpg', 'jpeg'].indexOf(item.split('.')[3]) != -1 ? 'image' : (['pdf'].indexOf(item.split('.')[3]) != -1 ? 'pdf' : 'video')
              }
            })
          }
          if (proof_images && proof_images.length) {
            proof_images = proof_images.map(item => {
              return {
                url: item,
                type: [ 'png', 'jpg', 'jpeg'].indexOf(item.split('.')[3]) != -1 ? 'image' : (['pdf'].indexOf(item.split('.')[3]) != -1 ? 'pdf' : 'video')
              }
            })
          }          
          if (invoice_images && invoice_images.length) {
            invoice_images = invoice_images.map(item => {
              return {
                url: item,
                type: [ 'png', 'jpg', 'jpeg'].indexOf(item.split('.')[3]) != -1 ? 'image' : (['pdf'].indexOf(item.split('.')[3]) != -1 ? 'pdf' : 'video')
              }
            })
          }
          this.setData({
            type, type_name, category, describe,other_desc,
            images,pay_images, appeal_type, order_code, store_name, store_number, arrival_time, contact_number, customer_name, remark,proof_images, status_name,typename,proname,feedback_id,pay_status,invoice_images,
            appeal_type_name: this.data.appealTypes.find(item => item.val == appeal_type).label
          })
        }
      })
      return
    }
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let timeList = [], dateList = getNearly7Day()
    for (let i = 6; i < 23; i++) {
      timeList.push(`${i}:00 - ${i}:30`)
      timeList.push(`${i}:30 - ${i + 1}:00`)
    }
    this.setData({
      timeList, dateList,
      selectTime: [0, 0],
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.removeStorage({
      key: 'myComplaint',
    })
  },

  // 上传图片视频
  chooseMedia() {
    common.chooseMedia(this, this.data.images, 9, 2, 20)
  },

  // 图片视频预览
  previewMedia(e) {
    const { current } = e.currentTarget.dataset;
    common.previewMedia(this.data.images, current)
  },

  
  // 上传付款图片
  choosePayMedia() {
    common.choosePayMedia(this, this.data.pay_images, 3, 2, 20)
  },
  // 图片付款图片
  previewPayMedia(e) {
    const { current } = e.currentTarget.dataset;
    common.previewMedia(this.data.pay_images, current)
  },
  downloadFile(e){
    const info = e.currentTarget.dataset;
    wx.showLoading({
      title: '下载中',
    });
    wx.downloadFile({
      url: info.url,
      success(res){
          wx.hideLoading();
          wx.openDocument({
            filePath: res.tempFilePath,
            success:function(res){

            }
          })
        console.log(res)
      }
    })
  },

  // 校验手机号
  checkTel(e) {
    let val = e.detail.value
    if (val && !reg.test(val)) {
      common.showToast('联系电话格式错误')
      return
    }
  },

  inputHandle(e) {
    this.setData({
      [e.currentTarget.dataset.param]: e.detail.value
    })
  },

  showPop(e) {
    if (this.data.isCheck) return
    const { param } = e.currentTarget.dataset
    this.selectComponent(`#${param}`).showPop()
    if (param == 'type') {
      setTimeout(() => {
        wx.createSelectorQuery().selectAll('.desc-box').boundingClientRect(res => {
          for (let i = 0; i < 2; i++) {
            this.data.complaintTypes[i].height = res[i].height
          }
        }).exec()
      }, 100);
    }
  },

  bindTimeChange(e) {
    this.selectTime = e.detail.value
  },

  timeConfirm() {
    const { dateList, timeList } = this.data
    this.setData({
      arrival_time: `${dateList[this.selectTime[0]]} ${timeList[this.selectTime[1]]}`
    })
    this.selectComponent('#time').hidePop()
  },

  bindTypeChange(e) {
    this.selectTypeIndex = e.detail.value[0]
  },

  typeConfirm() {
    const type = this.data.menus[this.selectTypeIndex].val
    this.setData({ type })
    if (type == 1 || type == 2) this.getStore()
    this.selectComponent('#type').hidePop()
  },

  addFeedback() {
    this.setData({ showStores: false })
    const { images, describe, contact_number, appeal_type } = this.data

    if (!contact_number) {
      common.showToast('请填写微信号')
      return
    }
    
    if (!this.isCansubmit) return
    this.isCansubmit = false
    // 向七牛云上传
    let i = 0, uploadImages = []
    common.showLoading('正在提交...')
    if (images.length) {
      const { envVersion } = wx.getAccountInfoSync().miniProgram
      const fileName = envVersion == 'release' ? 'wxtest2' : 'wxtest2'
      let flag = false
      images.forEach(({ url }, index) => {
        qiniuUploader.upload(url, res => {
          flag = flag || res.fileURL.indexOf('undefined') != -1
          uploadImages[index] = res.fileURL
          i += 1
          // 图片全部上传完再提交
          if (i == images.length) {
            if (uploadImages.length != images.length || flag) {
              common.showToast('部分文件上传失败，请稍后重试')
              this.isCansubmit = true
              return
            }
            this.submitForm(uploadImages)
          }
        }, error => {
          common.showToast('error: ' + error);
          this.isCansubmit = true
        }, {
          region: 'ECN',
          key: `${fileName}/${parseInt(new Date().getTime())}.${url.split('.')[1]}`, // 自定义上传文件名
        })
      })
      return
    }
    this.submitForm()
  },

  submitForm(uploadImages = []) {
    this.setData({type:"1",appeal_type:'1'});
    const { type, category, describe, appeal_type, order_id, order_code, store_id, store_name, store_number, arrival_time, contact_number, customer_name,proitem_id } = this.data
    server.postJSON(common.basePath + 'feedback/complain', {
      type, category, describe, appeal_type, order_id, order_code, store_id, store_name, store_number, arrival_time, contact_number, customer_name,proitem_id,
      images: uploadImages
    }, res => {
      const { errno, errmsg } = res.data;
      if (errno == '0') {
        common.showToast('提交成功')
        setTimeout(() => {
          wx.redirectTo({ url: 'records' })
        }, 500);
      } else {
        common.showErrorToast(errmsg);
      }
      setTimeout(() => {
        this.isCansubmit = true
      }, 500);
    })
  },
  addFeedbackPay() {
    this.setData({ showStores: false })
    const { pay_images } = this.data

    if (!pay_images) {
      common.showToast('请上传支付凭证')
      return
    }
    
    if (!this.isCansubmit) return
    this.isCansubmit = false
    // 向七牛云上传
    let i = 0, uploadImages = []
    common.showLoading('正在提交...')
    if (pay_images.length) {
      const { envVersion } = wx.getAccountInfoSync().miniProgram
      const fileName = envVersion == 'release' ? 'wxtest2' : 'wxtest2'
      let flag = false
      pay_images.forEach(({ url }, index) => {
        qiniuUploader.upload(url, res => {
          flag = flag || res.fileURL.indexOf('undefined') != -1
          uploadImages[index] = res.fileURL
          i += 1
          // 图片全部上传完再提交
          if (i == pay_images.length) {
            if (uploadImages.length != pay_images.length || flag) {
              common.showToast('部分文件上传失败，请稍后重试')
              this.isCansubmit = true
              return
            }
            this.submitFormPay(uploadImages)
          }
        }, error => {
          common.showToast('error: ' + error);
          this.isCansubmit = true
        }, {
          region: 'ECN',
          key: `${fileName}/${parseInt(new Date().getTime())}.${url.split('.')[1]}`, // 自定义上传文件名
        })
      })
      return
    }
    this.submitFormPay()
  },

  submitFormPay(uploadImages = []) {
    this.setData({type:"1",appeal_type:'1'});
    const { feedback_id } = this.data
    server.postJSON(common.basePath + 'feedback/edit', {
      feedback_id:feedback_id,
      pay_images: uploadImages
    }, res => {
      const { errno, errmsg } = res.data;
      if (errno == '0') {
        common.showToast('提交成功')
        setTimeout(() => {
          wx.redirectTo({ url: 'records' })
        }, 500);
      } else {
        common.showErrorToast(errmsg);
      }
      setTimeout(() => {
        this.isCansubmit = true
      }, 500);
    })
  },
  // 删除图片视频
  delMedia(e) {
    this.data.images.splice(e.currentTarget.dataset.index, 1)
    this.setData({ images: this.data.images })
  },
  // 删除付款图片视频
  delPayMedia(e) {
    this.data.pay_images.splice(e.currentTarget.dataset.index, 1)
    this.setData({ pay_images: this.data.pay_images })
  },
  radioChange(e) {
    if (this.data.isCheck) return
    const appeal_type = this.data.appealTypes[e.currentTarget.dataset.index].val
    if (appeal_type == this.data.appeal_type) return
    this.setData({
      appeal_type,
      showTipPop: appeal_type == 1 || appeal_type == 2
    })
  },

  getOrderList() {
    if (this.data.isLoading) return
    this.setData({ isLoading: true })
    if (this.page == 1) common.showLoading('获取订单中..')
    server.postJSON(common.storePath + 'order/lists', {
      status_select: 0,
      page: this.page,
      count: this.count,
      type: 1
    }, res => {
      if (this.page == 1) common.hideLoading()
      setTimeout(() => {
        this.setData({ isLoading: false })
      }, 100);
      let { errmsg, data, errno } = res.data;
      if (errno == '0') {
        if (data.length) {
          this.setData({
            orderList: this.page == 1 ? data : [...this.data.orderList, ...data],
            isNoMore: data.length < this.count
          })
          if (this.page == 1) {
            const { order_id, pay_code, status: { created_time }, store: { store_id, name, mobile } } = data[0]
            this.setData({
              selectedOrderId: order_id,
              order_code: pay_code,
              store_name: name,
              store_number: mobile,
              arrival_time: created_time,
              contact_number: data[0].mobile
            })
            this.data.order_id = order_id
            this.data.store_id = store_id
          }
        } else {
          this.setData({ isNoMore: true })
        }
      } else {
        common.showErrorToast(errmsg);
      }
    })
  },

  // 到达底部
  scrollToLower() {
    if (!this.data.isNoMore && !this.data.isLoading) {
      this.page += 1
      this.getOrderList()
    }
  },

  selectOrder(e) {
    const { order_id } = e.currentTarget.dataset
    this.setData({ selectedOrderId: this.data.selectedOrderId == order_id ? '' : order_id })
  },

  orderConfirm() {
    this.selectComponent('#order').hidePop()
    if (!this.data.selectedOrderId) {
      this.setData({
        order_code: '',
        store_name: '',
        store_number: '',
        arrival_time: '',
        contact_number: ''
      })
      this.data.order_id = ''
      this.data.store_id = ''
      return
    }
    const order = this.data.orderList.find(item => item.order_id == this.data.selectedOrderId)
    const { order_id, pay_code, status: { created_time }, store: { store_id, name, mobile } } = order
    this.setData({
      order_code: pay_code,
      store_name: name,
      store_number: mobile,
      arrival_time: created_time,
      contact_number: order.mobile
    })
    this.data.order_id = order_id
    this.data.store_id = store_id
  },

  hideOrderPop() {
    setTimeout(() => {
      if (this.data.selectedOrderId != this.data.order_id) {
        this.setData({ selectedOrderId: this.data.order_id })
      }
    }, 500);
  },

  expandHandle(e) {
    const { index } = e.currentTarget.dataset
    const { expanded, height } = this.data.complaintTypes[index]
    const animation = wx.createAnimation({
      duration: 0,
      timingFunction: 'ease-in-out',
    });
    if (expanded) {
      animation.height(height).top(0).step({ duration: 1 }).height(0).step({ duration: 300 });
    } else {
      animation.height(height).top(1).step({ duration: 300 }).height('auto').step()
    }
    this.setData({
      animation: animation.export(),
      curIndex: index,
      [`complaintTypes[${index}].expanded`]: !expanded
    })
  },

  selectType(e) {
    const { index, category } = e.currentTarget.dataset
    const { val, tit } = this.data.complaintTypes[index]
    this.setData({
      type: val,
      type_name: tit,
      category: category || ''
    })
    this.selectComponent('#type').hidePop()
  },

  callHandle() {
    if (!this.data.store_number) return
    wx.makePhoneCall({
      phoneNumber: this.data.store_number
    })
  },

  toRefund() {
    common.navigateTo({
      url: '../afterSaleService/index',
    })
  }

})